package com.rs.admin.sys.org.service.impl;

import com.rs.admin.sys.org.entity.User;
import com.rs.admin.sys.org.entity.UserToken;
import com.rs.admin.sys.org.mapper.UserMapper;
import com.rs.admin.sys.org.mapper.UserTokenMapper;
import com.rs.admin.sys.org.service.ShiroServcie;
import com.rs.admin.sys.pms.entity.Permission;
import com.rs.admin.sys.pms.mapper.PermissionMapper;
import com.rs.common.utils.constant.Constant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 权限认证服务实现
 * @author hedonglin
 * @company 睿思科技
 * @email 1048791780@qq.com
 * @date 2017年12月20
 */
@Service
public class ShiroServiceImpl implements ShiroServcie {
    @Autowired
    private UserTokenMapper userTokenMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 查询权限
     * @param userId
     * @return
     */
    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;

        //如果是开发人员
        if(userId == Constant.DEVELOPER){
            List<Permission> menuList = permissionMapper.selectByMap(new HashMap<>());
            permsList = new ArrayList<>(menuList.size());
            for(Permission p : menuList){
                permsList.add(p.getIdentify());
            }
        }else{
            permsList = userMapper.queryAllPerms(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    /**
     * 根据token查询用户id
     * @param token
     * @return
     */
    @Override
    public UserToken findByToken(String token) {
        //参数构造
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        //查询
        List<UserToken> list = userTokenMapper.selectByMap(map);
        if (list.size() > 0){
            return list.get(0);
        }
        return null;
    }

    /**
     * 根据id查询用户信息
     * @param id
     * @return
     */
    @Override
    public User findUserById(Long id) {
        User user = userMapper.selectById(id);
        return user;
    }
}
